﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System.Collections.Generic;
using System;
using ESRI.ArcGIS.esriSystem;
using MapFormsApp.Models;
using MapFormsApp.Helpers;

namespace MapFormsApp.Services
{
    /// <summary>
    /// 空间与属性查询服务（封装查询逻辑）
    /// </summary>
    public class QueryService
    {
        private readonly IMap _map;
        private readonly DataManager _dataManager;

        public QueryService(IMap map, DataManager dataManager)
        {
            _map = map;
            _dataManager = dataManager;
        }

        #region 空间查询
        /// <summary>
        /// 点选查询（返回包含点的要素）
        /// </summary>
        public List<Building> QueryByPoint(IPoint queryPoint, string layerName = "Buildings")
        {
            var results = new List<Building>();
            IFeatureLayer layer = FindLayerByName(layerName) as IFeatureLayer;
            if (layer == null) return results;

            ISpatialFilter spatialFilter = new SpatialFilter
            {
                Geometry = queryPoint,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            using (ESRI.ArcGIS.ADF.ComReleaser cr = new ESRI.ArcGIS.ADF.ComReleaser())
            {
                IFeatureCursor cursor = layer.Search(spatialFilter, false);
                cr.ManageLifetime(cursor);

                IFeature feature;
                while ((feature = cursor.NextFeature()) != null)
                {
                    results.Add(Building.FromFeature(feature));
                }
            }
            return results;
        }

        /// <summary>
        /// 缓冲区查询（返回缓冲区内的要素）
        /// </summary>
        public List<Building> QueryByBuffer(IPoint center, double radiusMeters, string layerName = "Buildings")
        {
            IGeometry buffer = GeometryHelper.CreateBuffer(center, radiusMeters, esriUnits.esriMeters);
            return SpatialQuery(buffer, layerName);
        }

        /// <summary>
        /// 通用空间查询（支持任意几何范围）
        /// </summary>
        public List<Building> SpatialQuery(IGeometry queryGeometry, string layerName = "Buildings")
        {
            var results = new List<Building>();
            IFeatureLayer layer = FindLayerByName(layerName) as IFeatureLayer;
            if (layer == null) return results;

            ISpatialFilter spatialFilter = new SpatialFilter
            {
                Geometry = queryGeometry,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            using (ESRI.ArcGIS.ADF.ComReleaser cr = new ESRI.ArcGIS.ADF.ComReleaser())
            {
                IFeatureCursor cursor = layer.Search(spatialFilter, false);
                cr.ManageLifetime(cursor);

                IFeature feature;
                while ((feature = cursor.NextFeature()) != null)
                {
                    results.Add(Building.FromFeature(feature));
                }
            }
            return results;
        }
        #endregion

        #region 属性查询
        /// <summary>
        /// 按建筑名称模糊查询
        /// </summary>
        public List<Building> QueryByName(string nameKeyword, string layerName = "Buildings")
        {
            var results = new List<Building>();
            IFeatureLayer layer = FindLayerByName(layerName) as IFeatureLayer;
            if (layer == null) return results;

            IQueryFilter queryFilter = new QueryFilter
            {
                WhereClause = $"BldgName LIKE '%{nameKeyword}%'"
            };

            using (ESRI.ArcGIS.ADF.ComReleaser cr = new ESRI.ArcGIS.ADF.ComReleaser())
            {
                IFeatureCursor cursor = layer.Search(queryFilter, false);
                cr.ManageLifetime(cursor);

                IFeature feature;
                while ((feature = cursor.NextFeature()) != null)
                {
                    results.Add(Building.FromFeature(feature));
                }
            }
            return results;
        }

        /// <summary>
        /// 按建筑ID精确查询
        /// </summary>
        public Building QueryByID(string bldgID, string layerName = "Buildings")
        {
            IFeatureLayer layer = FindLayerByName(layerName) as IFeatureLayer;
            if (layer == null) return null;

            IQueryFilter queryFilter = new QueryFilter
            {
                WhereClause = $"BldgID = '{bldgID}'"
            };

            using (ESRI.ArcGIS.ADF.ComReleaser cr = new ESRI.ArcGIS.ADF.ComReleaser())
            {
                IFeatureCursor cursor = layer.Search(queryFilter, false);
                cr.ManageLifetime(cursor);
                return Building.FromFeature(cursor.NextFeature());
            }
        }
        #endregion

        #region 辅助方法
        private ILayer FindLayerByName(string layerName)
        {
            for (int i = 0; i < _map.LayerCount; i++)
            {
                ILayer layer = _map.get_Layer(i);
                if (layer.Name.Equals(layerName, StringComparison.OrdinalIgnoreCase))
                {
                    return layer;
                }
            }
            return null;
        }
        #endregion
    }
}